package com.xauto.pioneer.appuser.activity.mine.balance;

import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.AccountInfoCallBack;
import com.xauto.pioneer.appuser.model.AccountInfo;
import com.xauto.pioneer.appuser.model.Bank;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.MemberAccount;
import com.xauto.pioneer.appuser.util.CashierInputFilter;
import com.xauto.pioneer.appuser.util.DataCheckUtil;
import com.xauto.pioneer.appuser.util.DataLoadUtil;
import com.xauto.pioneer.appuser.util.PreferencesUtils;
import com.xauto.pioneer.appuser.util.SerializeUtil;
import com.xauto.pioneer.appuser.util.StringUtils;
import com.xauto.pioneer.appuser.util.ViewUtil;
import com.xauto.pioneer.appuser.view.PromptDialog;
import com.xauto.pioneer.appuser.view.TopBar;

import net.tsz.afinal.FinalDb;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/***
 * 账户余额提现 页面
 *
 * @author Lemon Tue 7 Mar 18:32
 */
public class AccountWithdrawActivity extends BaseActivity implements TextWatcher{

    @Bind(R.id.topBar) TopBar topBar;
    /** 输入-提现金额*/
    @Bind(R.id.etAccountWithDrawAmount) EditText etAccountWithDrawAmount;
    /** 显示-当前余额*/
    @Bind(R.id.tvAccountWithDrawAmount) TextView tvAccountWithDrawAmount;
    /** 输入-银行卡号*/
    @Bind(R.id.etAccountWithDrawBankNum) EditText etAccountWithDrawBankNum;
    /** 输入-银行持卡人姓名*/
    @Bind(R.id.etAccountWithDrawBankName) EditText etAccountWithDrawBankName;
    @Bind(R.id.tvAccountWithDraw) TextView tvAccountWithDraw;
    @Bind(R.id.etAccountWithDrawBankType) TextView etAccountWithDrawBankType;
    private PromptDialog promptDialog;
    MemberAccount memberAccount;
    //会员账户信息
    AccountInfo accountInfo;
    //会员账户ID
    String member_account_id = "";
    //ID
    String bankId = "";
    @Override
    protected int getContentView() {
        return R.layout.ac_account_withdraw;
    }

    @Override
    protected void initView() {
        topBar.showView(TopBar.LEFT_IMAGE_BTN, TopBar.TITLE);
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        topBar.setText(TopBar.TITLE, R.string.account_withdraw);
        topBar.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        etAccountWithDrawAmount.addTextChangedListener(this);
        etAccountWithDrawBankNum.addTextChangedListener(this);
        etAccountWithDrawBankName.addTextChangedListener(this);
        promptDialog = new PromptDialog(mContext, getString(R.string.notice), getString(R.string.text_not_network),
                getString(R.string.to_setting), getString(R.string.logout),getString(R.string.dialogpic_notice), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //去设置
                promptDialog.dismiss();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出
                promptDialog.dismiss();
            }
        });
        //输入金额拦截
        InputFilter[] inputFilters = {new CashierInputFilter()};
        etAccountWithDrawAmount.setFilters(inputFilters);
    }

    @Override
    protected void initData() {
        //显示余额
        memberAccount = DataCheckUtil.getMemberObj(mContext).member_account_info;
        tvAccountWithDrawAmount.setText(getResources().getString(R.string.current_account,memberAccount.balance_amount));
        accountInfo = (AccountInfo)SerializeUtil.deSerialization(PreferencesUtils.getString(mContext,Constants.KEY_MEMBER_ACCOUNT_OBJECT));
        showData();
        //再次预加载
        DataLoadUtil.getMemberAccountInfo(mContext, new AccountInfoCallBack() {
            @Override
            public void getAccountInfo(AccountInfo info) {
                accountInfo = info;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showData();
                    }
                });
            }
        });
    }

    /**
     * 回显相关数据
     */
    private void showData(){
        FinalDb finalDb = FinalDb.create(mContext);
        List<Bank> bankList = finalDb.findAll(Bank.class);
        // 根据a-z进行排序源数据
        Collections.sort(bankList,new PinyinComparator());
        if (bankList != null && bankList.size() > 0){
            etAccountWithDrawBankType.setText(bankList.get(0).getBank_name());
            bankId = bankList.get(0).getBank_id();
        }
        if (accountInfo != null){
            member_account_id = accountInfo.member_account_id;
            etAccountWithDrawBankType.setText(accountInfo.bank_name);
            etAccountWithDrawBankNum.setText(accountInfo.bank_account_number);
            etAccountWithDrawBankName.setText(accountInfo.bank_account_name);
        }
    }
    @OnClick({R.id.tvAccountWithDrawAll, R.id.tvAccountWithDraw})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvAccountWithDrawAll:
                //全部提现
                etAccountWithDrawAmount.setText(memberAccount.balance_amount);
                break;
            case R.id.tvAccountWithDraw:
                //提现
                String accountStr = etAccountWithDrawAmount.getText().toString().trim();
                String accountBankNum = etAccountWithDrawBankNum.getText().toString().trim();
                String accountBankName = etAccountWithDrawBankName.getText().toString().trim();
                submitTransaction(accountStr,accountBankNum,accountBankName);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        showBtnView();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 显示‘申请提现’按钮是否可点击及颜色设置
     */
    private void showBtnView(){
        String accountStr = etAccountWithDrawAmount.getText().toString().trim();
        String accountBankNum = etAccountWithDrawBankNum.getText().toString().trim();
        String accountBankName = etAccountWithDrawBankName.getText().toString().trim();
        if (!StringUtils.isBlank(accountStr) && !StringUtils.isBlank(accountBankNum) && !StringUtils.isBlank(accountBankName)){
            ViewUtil.GetViewShgape(tvAccountWithDraw);
            tvAccountWithDraw.setClickable(true);
            tvAccountWithDraw.setBackgroundResource(R.drawable.bg_btn_green_selector);
            ViewUtil.SetViewShgape(tvAccountWithDraw);
        }else {
            ViewUtil.GetViewShgape(tvAccountWithDraw);
            tvAccountWithDraw.setClickable(false);
            tvAccountWithDraw.setBackgroundResource(R.drawable.bg_btn_gray);
            ViewUtil.SetViewShgape(tvAccountWithDraw);
        }
    }

    private void submitTransaction(String account,String bankNo,String bankName){
        new LHttpLib().submitAmountTransaction(mContext,memberId,account,member_account_id,bankId,
                bankName,bankNo,new BaseLHttpHandler(mContext,true,true){
                    @Override
                    public void onSuccess(JSONStatus jsonStatus) {
                        super.onSuccess(jsonStatus);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                prompt("申请提现成功");
                                finish();

                            }
                        });
                    }
                });
    }
    @OnClick(R.id.etAccountWithDrawBankType)
    public void onViewClicked() {
        startActivityForResult(new Intent(mContext,BankListActivity.class),100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK){
            etAccountWithDrawBankType.setText(data.getStringExtra("bank_name"));
            bankId = data.getStringExtra("bank_id");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    public class PinyinComparator implements Comparator<Bank> {

        public int compare(Bank o1, Bank o2) {
            if (o1.getBank_prefix().equals("@")
                    || o2.getBank_prefix().equals("#")) {
                return -1;
            } else if (o1.getBank_prefix().equals("#")
                    || o2.getBank_prefix().equals("@")) {
                return 1;
            } else {
                return o1.getBank_prefix().compareTo(o2.getBank_prefix());
            }
        }

    }
}
